<template>
	<div class="register">
		<p class="register__header">账号注册</p>
		<el-form
			class="register__body"
			ref="form"
			:model="accountInfo"
			:rules="accountRules"
			auto-complete="on"
			label-width="80px"
		>
			<!-- <el-form-item label="头像:">
				<avatar-upload
					v-model="accountInfo.avatar"
					action="http://localhost:8080/upload"
					name="file"
					style="margin-left:60px"
				/>
			</el-form-item> -->
			<el-form-item label="用户名" prop="username">
				<el-input v-model="accountInfo.username" placeholder="请输入用户名"></el-input>
			</el-form-item>
			<el-form-item label="账号" prop="account">
				<el-input v-model="accountInfo.account" placeholder="请输入账号"></el-input>
			</el-form-item>

			<el-form-item label="密码" prop="password">
				<el-input v-model="accountInfo.password" type="password" placeholder="请输入密码"></el-input>
			</el-form-item>

			<el-form-item label="确认密码" prop="checkPassword">
				<el-input v-model="accountInfo.checkPassword" type="password" placeholder="请再次输入密码"></el-input>
			</el-form-item>

			<el-form-item label="手机号" prop="phone">
				<el-input v-model="accountInfo.phone" placeholder="请填写手机号码"></el-input>
			</el-form-item>
			<el-form-item label="验证码" prop="code">
				<el-input v-model="accountInfo.code" placeholder="请输入随机码" style="width:50%"></el-input>
				<canvas id="canvas"></canvas>
			</el-form-item>
			<el-form-item label="密令" prop="passCode">
				<el-input v-model="accountInfo.passCode" placeholder="请填写8-18位密令" type="password"></el-input>
			</el-form-item>
			<P style="font-size:12px;color:red;padding-left:80px">注：密令为个人信息及密码修改的唯一凭证，请严格保管！</P>
			<el-form-item label="性别" prop="sex">
				<el-radio v-model="radio" label="男">男</el-radio>
				<el-radio v-model="radio" label="女">女</el-radio>
			</el-form-item>
			<el-form-item>
				<el-col :span="11">
					<el-button
						style="width: 100%"
						type="primary"
						:loading="registerLoading"
						@click="handleRegister"
					>注册</el-button>
				</el-col>
				<el-col :span="11" :offset="2">
					<router-link to="/">使用已有账号登录</router-link>
				</el-col>
			</el-form-item>
		</el-form>
	</div>
</template>

<script>
import AvatarUpload from '@/components/business/upload/avatar-upload'
import { register, upload } from '../../../api/request.js'
export default {
	components: {
		AvatarUpload,
	},
	mounted() {
		let canvas = document.getElementById('canvas') //画布对象
		let show_num = [] //装验证码的数组
		//产生随机颜色
		function randomColor() {
			var r = Math.floor(Math.random() * 256)
			var g = Math.floor(Math.random() * 256)
			var b = Math.floor(Math.random() * 256)
			return 'rgb(' + r + ',' + g + ',' + b + ') '
		}
		//画布
		function draw(show_num) {
			let canvas_clientWidth = document.getElementById('canvas').clientWidth //画布长度
			let canvas_clientHeight = document.getElementById('canvas').clientHeight //画布高度
			let context = canvas.getContext('2d') //画布环境 创建 context 对象：
			canvas.width = canvas_clientWidth
			canvas.height = canvas_clientHeight
			let str =
				'1,2,3,4,5,6,7,8,9,0,q,w,e,r,t,y,u,i,o,p,a,s,d,f,g,h,j,k,l,z,x,c,v,b,n,m'
			let astr = str.split(',') //分割字符串形成数组
			let sLength = astr.length //数组长度
			for (let i = 0; i <= 3; i++) {
				let j = Math.floor(Math.random() * sLength) //随机索引
				let deg = (Math.random() * 30 * Math.PI) / 180 //0-30随机弧度
				let text = astr[j] //随机字符
				show_num[i] = text //验证码字符数组
				let x = 10 + i * 20 //x坐标
				let y = 20 + Math.random() * 8 //y坐标
				//位移 旋转角度 颜色 文字 样式开始位置
				context.font = 'bold 23px 微软雅黑'
				context.translate(x, y)
				context.rotate(deg)
				context.fillStyle = randomColor()
				context.fillText(text, 0, 0)
				context.rotate(-deg)
				context.translate(-x, -y)
			}
			//验证码显示小点
			for (let i = 0; i <= 30; i++) {
				context.strokeStyle = randomColor() //设置随机色用小点的颜色
				context.beginPath() //开始一条路径
				let m = Math.random() * canvas_clientWidth
				let n = Math.random() * canvas_clientHeight
				context.moveTo(m, n) //移动
				context.lineTo(m + 1, n + 1) //添加一个新点，然后在画布中创建从该点到最后指定点的线条
				context.stroke() //画上面定义好的路径
			}
			//验证码显示线条
			for (let i = 0; i < 8; i++) {
				context.strokeStyle = randomColor()
				context.beginPath()
				context.moveTo(Math.random() * canvas_clientWidth, Math.random() * canvas_clientHeight)
				context.lineTo(Math.random() * canvas_clientWidth, Math.random() * canvas_clientHeight)
				context.stroke()
			}
		}
		draw(show_num)
		canvas.onclick = () => {
			draw(show_num)
			console.log(show_num)
			this.show_num = show_num
		}
		this.show_num = show_num
	},
	data() {
		const validatePass = (rule, value, callback) => {
			if (value === '') {
				callback(new Error('请输入密码'))
			} else if (!/\d/.test(value) || !/[a-zA-Z]/.test(value)) {
				callback(new Error('密码至少要包含数字和字母'))
			} else {
				if (this.accountInfo.checkPassword !== '') {
					this.$refs.form.validateField('checkPassword')
				}
				callback()
			}
		}
		const validatePass2 = (rule, value, callback) => {
			if (value === '') {
				callback(new Error('请再次输入密码'))
			} else if (value !== this.accountInfo.password) {
				callback(new Error('两次填写的密码不一致'))
			} else {
				callback()
			}
		}
		return {
			registerLoading: false,
			captchaLoading: false,
			captchaButtonText: '获取验证码',
			radio: '',
			show_num: [],
			accountInfo: {
				username: '',
				password: '',
				checkPassword: '',
				phone: '',
				captcha: '',
				avatar: '',
				code: '',
				passCode: '',
			},
			accountRules: {
				username: [
					{
						required: true,
						message: '用户名不能为空',
						trigger: 'blur',
					},
				],
				account: [
					{
						required: true,
						message: '账号不能为空',
						trigger: 'blur',
					},
				],
				code: [
					{
						required: true,
						message: '验证码不能为空',
						trigger: 'blur',
					},
				],
				passCode: [
					{
						required: true,
						message: '密令不能为空',
						trigger: 'blur',
					},
					{
						pattern: /^[\w]{8,18}$/,
						message: '密令格式不正确',
						trigger: 'blur',
					},
				],
				password: [
					{
						required: true,
						message: '请输入密码',
						trigger: 'blur',
					},
					{
						validator: validatePass,
						trigger: 'blur',
					},
					{
						min: 6,
						max: 20,
						message: '密码长度为6~20位',
						trigger: 'blur',
					},
				],
				checkPassword: [
					{
						required: true,
						message: '请再次输入密码',
						trigger: 'blur',
					},
					{
						validator: validatePass2,
						trigger: 'blur',
					},
				],
				phone: [
					{
						required: true,
						message: '请填写手机号',
						trigger: 'blur',
					},
					{
						pattern: /^1[345789]\d{9}$/,
						message: '手机号码格式不正确',
						trigger: 'blur',
					},
				],
				captcha: [
					{
						required: true,
						message: '请填写验证码',
						trigger: 'blur',
					},
				],
			},
		}
	},
	methods: {
		// 设置获取验证码按钮的默认状态
		setDefaultCaptchaButton(timer) {
			clearInterval(timer)
			this.captchaLoading = false
			this.captchaButtonText = '获取验证码'
		},
		// 校验手机号
		validPhone(phone) {
			if (!phone.match(/^1[345789]\d{9}$/)) {
				this.$message.error('请填写正确的手机号！')
				return false
			}
			return true
		},
		//获取验证码
		async getCaptcha() {
			if (!this.validPhone(this.accountInfo.phone)) return
			// 倒计时
			this.captchaLoading = true
			let totalTime = 60
			let timer = null
			timer = setInterval(() => {
				totalTime--
				if (totalTime > 0) {
					this.captchaButtonText = `获取验证码(${totalTime}s)`
				} else {
					this.setDefaultCaptchaButton(timer)
				}
			}, 1000)

			await this.$api.account.getCaptcha({ phone: this.accountInfo.phone })
			this.$message.success(`验证码已发送至手机${this.accountInfo.phone}，请注意查收！`)
		},
		// 注册
		async handleRegister() {
			let str = this.show_num.join('')
			if (this.accountInfo.code !== str) {
				this.$message.warning('请填写正确信息')
				this.registerLoading = false
				return false
			}
			if (!/^1[3456789]\d{9}$/.test(this.accountInfo.phone)) {
				this.$message.warning('请填写正确信息')
				this.registerLoading = false
				return false
			}
			if (!/^[\w]{8,18}$/.test(this.accountInfo.passCode)) {
				this.$message.warning('请填写正确信息')
				this.registerLoading = false
				return false
			}
			if (
				this.accountInfo.password !== this.accountInfo.checkPassword ||
				this.accountInfo.password.length < 6 ||
				this.accountInfo.password.length > 20 ||
				this.accountInfo.account === '' ||
				this.accountInfo.code === '' ||
				this.radio === '' ||
				this.accountInfo.username === '' ||
				this.accountInfo.passCode === ''
			) {
				this.$message.warning('请按正确格式填写信息')
				this.registerLoading = false
				return false
			}
			let res = await register({
				u_name: this.accountInfo.username,
				account: this.accountInfo.account,
				password: this.accountInfo.password,
				phone: this.accountInfo.phone,
				sex: this.radio,
				jurisdiction: 'ordinary',
				passCode: this.accountInfo.passCode,
			})
			// jurisdiction ：ordinary 普通用户 ，vip:vip用户 ，admin：管理员， superAdmin：超级管理员
			// console.log(
			// 	this.accountInfo.username,
			// 	this.accountInfo.account,
			// 	this.accountInfo.phone,
			// 	this.accountInfo.code,
			// 	this.radio
			// )
			if (res.state === 'OK') {
				this.$message.success('注册成功！')
				this.$router.replace('/')
				this.registerLoading = false
			} else {
				this.$message.error(res.data)
			}

			// this.registerLoading = true
			// this.$refs.form.validate(async valid => {
			// 	if (valid) {
			// 		await this.$api.account.register(this.accountInfo)
			// 		this.$message.success('注册成功！')
			// 		await this.$store.dispatch('login', {
			// 			username: this.accountInfo.username,
			// 			password: this.accountInfo.password,
			// 		})
			// 		this.$router.replace('/')
			// 		this.registerLoading = false
			// 	} else {
			// 		this.$message.warning('请按正确格式填写信息')
			// 		this.registerLoading = false
			// 	}
			// })
		},
	},
}
</script>

<style lang="scss" scoped>
.register {
	padding: 15px 20px;
	/* background-color: rgba(255, 255, 255, 0); */
	box-shadow: 0px 0px 20px 0px rgba(0, 0, 0, 0.7);
	border-radius: 10px;
		opacity: 0.9;

	.register__header {
		font-size: 22px;
		text-align: center;
		color: #fff;
	}

	.register__body {
		margin-top: 20px;
	}
}
</style>

<style lang="scss">
.register {
	.el-form-item__label {
		color: #fff;
	}
}
#canvas {
	width: 130px;
	height: 45px;
	display: inline-block;
	border: 1px solid #c9c9c9;
	border-radius: 5px;
	position: absolute;
	right: 6px;
	top: -7px;
}
</style>
